package com.app.model.xml 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import com.peachcastle.debug.Log;
	
	[Event(name = "complete", type = "flash.events.Event")]
	
	public class XmlManager extends EventDispatcher 
	{
		
		private var _resource:Array =  null;
		
		private var _loader:URLLoader = null;
		
		private var _request:URLRequest = null;
		
		private var _index:int
		public function XmlManager() 
		{
			_resource = [];
			
			_request = new URLRequest();
			
			_loader = new URLLoader();
			_loader.dataFormat = URLLoaderDataFormat.BINARY;
			_loader.addEventListener(Event.COMPLETE, onComplete);
			_loader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
		}
		
		private function onError(event:IOErrorEvent):void
		{
			Log.debug("xml onError");
		}
		
		private function onProgress(event:ProgressEvent):void
		{
			
		}
		private function onComplete(event:Event):void
		{
			var byte:ByteArray = _loader.data;
			byte.uncompress();
			
			XmlItem(_resource[_index]).data = new XML(byte);
			
			if (_index < _resource.length - 1)
			{
				_index ++;
				start();
			}
			else
			{
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		public function addFile(url:String = "", label:String = "xml"):void
		{
			var item:XmlItem = new XmlItem();
			item.label = label;
			item.url = url;
			_resource[_resource.length] = item;
			item = null;
		}
		
		public function start():void
		{
			if (_resource.length < 1) return;
			_request.url = XmlItem(_resource[_index]).url;
			
			_loader.load(_request);
			
		}
		
		public function getLabelByXML(label:String = ""):XML
		{
			for each(var item:XmlItem in _resource)
			{
				if (item.label == label) return item.data;
			}
			
			return null;
		}
	}

}